TOOL.Category		= "Construction"
TOOL.Name			= "SRemover"
TOOL.Command		= nil
TOOL.ConfigName		= ""
TOOL.busy           =false

--the default settings
TOOL.ClientConVar["radius"]=128
TOOL.ClientConVar["maxremovespp"]=1



--notifygap is the multiple of which the player will be informed of the smartweld progress (ie. weld 50, 100, 150 placed)
NOTIFYGAP=25


if ( CLIENT ) then

	language.Add( "Tool_SRemover_name", "SRemover" )
	language.Add( "Tool_SRemover_desc", "Select props or a radius around a prop to remove" )
	language.Add( "Tool_SRemover_0", "Select props with left click (hold use key and left click to auto-select). Remove with right click. Reload clears selection." )

end


function TOOL:LeftClick( trace )

	if(!self.busy) then
    if(self.props==nil) then
	      self.props={}
	end
	
	for a,v in ipairs(self.props) do
			--Msg("V="..v.."\n")
			if(!v.ent:IsValid()) then
				table.remove(self.props,a)
				--Msg("Removing...\n")
			end
	end
    --Msg("Start\n")
	if (!trace.HitPos) then return false end
	if (trace.Entity:IsPlayer()) then return false end
	
	if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end
	
	if ( CLIENT ) then return true end
	
	// Get client's CVars
	local ply = self:GetOwner()
	
	local radius=self:GetClientNumber("radius")
	
	if ( trace.Entity:IsValid() && trace.Entity:GetPhysicsObject():IsValid()) then
	   if(ply:KeyDown(IN_USE)||ply:KeyDown(IN_SPEED)) then
	   
	        --autoselect
	        
			local selectedcount=self:Autoselect(trace.Entity,radius)
			if(selectedcount>1) then
		    self:GetOwner():PrintMessage(HUD_PRINTCENTER,selectedcount.." props auto-selected")
		    end
	   
       else
	
	   	   self:ChooseEnt(trace.Entity)
	   end
	end
	--Msg("End\n")
	return true
	else
	return false
	end
	
end

function TOOL:Autoselect(ent,radius)
		 local counted=0
         if ( ent:IsValid() && ent:GetPhysicsObject():IsValid() && !ent:IsPlayer()) then

            if(!self:IsSelected(ent)) then
            
                if(self:IsPropOwner(self:GetOwner(),ent)) then
                
                --add to list, try adding everything near it to list
            	self:SelectEnt(ent,false)
            	counted=1
            	
            	local close_ents = ents.FindInSphere( ent:GetPos(), radius )
            	
            	for i,v in ipairs(close_ents) do
            	    if(v!=ent) then
            	        counted=counted+self:Autoselect(v,radius)
            	    end
            	end
            	end
			end
         end
         return counted
end

function TOOL:IsSelected(ent)

    	 local selected=-1
       for i,v in ipairs(self.props) do
           if(v.ent==ent) then
		   selected=i
		   break
		   end
	   end
	   
	   if(selected==-1) then
	        return false
		else
		    return true
	   end

end

function TOOL:IsPropOwner(ply, ent)

	if(USEPROPPROTECTION) then
	for k, v in pairs(g_SBoxObjects) do
		for b, j in pairs(v) do
			for _, e in pairs(j) do
				if(e == ent) then
					if(k == ply:UniqueID()) then
						return true
					end
				end
			end
		end
	end

	for k, v in pairs(GAMEMODE.CameraList) do
		for b, j in pairs(v) do
			if(j == ent) then
				if(k == ply:UniqueID()) then
					return true
				end
			end
		end
	end
	return false
	else
	return true
	end
end

function TOOL:ChooseEnt(ent)

		  if(self:IsPropOwner(self:GetOwner(),ent)) then
		  
	         local selected=-1
	       for i,v in ipairs(self.props) do
	           if(v.ent==ent) then
			   selected=i
			   break
			   end
		   end
	         if(selected==-1) then
		       --Msg("Setting colour\n")
		       local r,g,b,a = ent:GetColor();
			   table.insert(self.props,{ent=ent,r=r,g=g,b=b,a=a})
			   ent:SetColor(255,0,0,255)
		   else
			   ent:SetColor(self.props[selected].r,self.props[selected].g,self.props[selected].b,self.props[selected].a)
			   table.remove(self.props,selected)
		   end
	   end
end




function TOOL:DeselectEnt(ent)

         if(self:IsPropOwner(self:GetOwner(),ent)) then
         local selected=-1
       for i,v in ipairs(self.props) do
           if(v.ent==ent) then
		   selected=i
		   break
		   end
	   end
         if(selected==-1) then

	   else
       	   ent:SetColor(self.props[selected].r,self.props[selected].g,self.props[selected].b,self.props[selected].a)
		   table.remove(self.props,selected)
	   end
	   end
end



function TOOL:SelectEnt(ent)

   if(self:IsPropOwner(self:GetOwner(),ent)) then
    local r,g,b,a = ent:GetColor();
	table.insert(self.props,{ent=ent,r=r,g=g,b=b,a=a})
	ent:SetColor(255,0,0,255)
   end

end

function TOOL:RemovingFinished(removecount, holdinguse, proptable,ply)
		 undo.SetPlayer( ply )
			undo.Finish()
			
			
			if(holdinguse) then
			    if(removecount!=1) then
      				self:GetOwner():PrintMessage(HUD_PRINTCENTER,"SRemover complete! "..removecount.." props where removed")
		    	else
      			self:GetOwner():PrintMessage(HUD_PRINTCENTER,"SRemover complete! "..removecount.." props where removed")
		    	end

			else

				if(removecount!=1) then
			    self:GetOwner():PrintMessage(HUD_PRINTCENTER,"SRemover complete! "..removecount.." props where removed")
			    else
			    self:GetOwner():PrintMessage(HUD_PRINTCENTER,"SRemover complete! "..removecount.." props where removed")
			    end
		    end
		    
		    --deselect
		    self.busy=false
		    self:ResetSelection()
		    
		    --Msg("SRemove complete!\n")
end

function TOOL:RemoveEnts(ent1, ent2,bone1, bone2, removecount)

         if(ent1:IsValid() and ent2:IsValid()) then
	         local const = constraint.Remove( ent1, ent2, bone1, bone2 )
			 undo.AddEntity( const )

			 if(((removecount+1)%NOTIFYGAP)==0) then

			 		self:GetOwner():PrintMessage(HUD_PRINTCENTER,"remove "..(removecount+1).." removed")

			 end
		 end

end


 function TOOL:RightClick( trace )
 
 local function RemoveEntity( ent )
  
     if (ent:IsValid()) then
         ent:Remove()
     end
	if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end

	if ( CLIENT ) then return true end
  
 end
  
  
 local function DoRemoveEntity( Entity )
  
     if (!Entity) then return false end
     if (!Entity:IsValid()) then return false end
     if (Entity:IsPlayer()) then return false end
  
     // Nothing for the client to do here
     if ( CLIENT ) then return true end
  
     // Remove all constraints (this stops ropes from hanging around)
     constraint.RemoveAll( Entity )
    
     // Remove it properly in 1 second
     timer.Simple( 1, RemoveEntity, Entity )
    
     // Make it non solid
     Entity:SetNotSolid( true )
     Entity:SetMoveType( MOVETYPE_NONE )
     Entity:SetNoDraw( true )
    
     // Send Effect
     local ed = EffectData()
         ed:SetEntity( Entity )
     util.Effect( "entity_remove", ed, true, true )
   
  return true
  
 end 
  
      if not self.props then -- if self.props == nil it acts as if self.props = false when used in boolean logic
          self.props = {}
      end
  
      if self.busy then return false end
    
      -- #table is the number of entries in that table.
      --If there are no entities in our prop table, then we can't do anything.
      if #self.props < 1 then return false end
    
      for k,v in pairs(self.props) do
          -- No need to check if the entity is valid, as DoRemoveEntity does that for us
          DoRemoveEntity(v.ent)
      end
    
       self.props = {} -- Clear the table
    
     return true -- Returning true under this function makes the tool do its sounds/effects
    
  end 

function TOOL:ResetSelection()

		 local ply=self:GetOwner()
		 
		 local propscleared=false
		   --clear the selection
		   if(self.props==nil) then
			      self.props={}
			end
			for a,v in ipairs(self.props) do
					--Msg("V="..v.."\n")
					if(!v.ent:IsValid()) then
						table.DoRemove(self.props,a)
						--Msg("Removing...\n")
					end
			end
			
			if(#self.props>0) then
			   for a,v in ipairs(self.props) do
			       if(v.ent:IsValid()) then
			       	 v.ent:SetColor(v.r,v.g,v.b,v.a)
			       end
				end
				propscleared=true
				
		   end
		   
		   self.props={}
		   return propscleared
		   
end

function TOOL:Reload( trace )

		 if(!self.busy) then
		 local cleared=self:ResetSelection()
		 
		 if(cleared) then
		 			 self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Selection cleared!")
		 end
		 end
         

end

 

function TOOL.BuildCPanel(cp)

    cp:AddControl( "Header", { Text = "SRemover", Description	= "Remove things that you select." }  )
    cp:AddControl( "Slider", { Label = "Auto-select Radius:", Description = "The autoselecting radius (hold use and left click to autoselect)",Type = "float", Min = "0", Max = "1000", Command = "radius" } )


end
